import { OneModal } from '@/components/one-ui';
import { IOneModalRef } from '@/pages/type';
import { Ref, useEffect, useRef, useState } from 'react';
import { IResourMenuModalProp } from '../type';
import { Button, Col, Form, Input, InputNumber, message, Row, Select, Spin, Tooltip, TreeSelect } from 'antd';
import { addEditResoucer, useResourVierInfo } from '../hooks/useResManageReq';
import pageStyles from '@/common/pageLayout.less';
import { useRequest } from 'umi';
import { loadMdicMap } from '@/services/BaseLayout';
import { getCompanyID, getPosIDs, getTenantID, getUserDepID, getUserID, treeSelectIconTransform } from '@/utils';
import MyIcon from '@/components/MyIcon';
import { QuestionCircleOutlined } from '@ant-design/icons';

export const ResoucerAddEditModal: React.FC<IResourMenuModalProp> = ({
  onClose, //关闭modal
  editAddRows,
  visible,
  rouTreeData, //上级资源数据源
  tableReload,
}) => {
  // const prefixModal = 'edit-modal';
  const ResourModalRef: Ref<IOneModalRef> = useRef(null); //弹框的ref
  const { detailInfoData, infoLoading } = useResourVierInfo(editAddRows); //获取详情信息
  const [resourForm] = Form.useForm();
  // 保存搜索框输入的值
  const [treeSearch, setTreeSearch] = useState<string>('');
  // 保存图标改变显示
  const [selectedIcon, setSelectedIcon] = useState<string>('');
  const changeIcon = (iconStr: string) => {
    setSelectedIcon(iconStr);
  };

  /**
   * 是否展示类别提示图标
   */
  const [isResoucerStyleTip, setIsResoucerStyleTip] = useState<boolean>(false);

  /* 关闭弹窗 */
  // const onCloseModal = (e: React.MouseEvent<HTMLElement, MouseEvent>) => {
  const onCloseModal = () => {
    if (ResourModalRef) {
      if (ResourModalRef.current) {
        if (ResourModalRef.current.onModalCancel) {
          ResourModalRef.current.onModalCancel();
        }
      }
    }
  };

  // 获取数据字典
  const MapList = useRequest(() => {
    return loadMdicMap([`${getTenantID()}0000`]);
  });

  useEffect(() => {
    if (detailInfoData && detailInfoData?.id && visible) {
      resourForm?.setFieldsValue(detailInfoData);

      if (detailInfoData?.resourceStyle == 0) {
        setIsResoucerStyleTip(true);
      } else {
        setIsResoucerStyleTip(false);
      }
    } else {
      setIsResoucerStyleTip(true);
    }
  }, [detailInfoData?.versionNum, visible]);

  // 获取搜索框输入的值
  const treeSearchValue = (valText: string) => {
    setTreeSearch(valText);
  };

  // 处理树数据
  const handleSelectTree = (list: any) => {
    return list?.map((item: any) => {
      const index = item?.name ? item?.name.indexOf(treeSearch) : -1;
      const beforeStr = item?.name ? item?.name.substr(0, index) : '';
      const afterStr = item?.name ? item?.name.substr(index + treeSearch.length) : '';
      const title =
        index > -1 && treeSearch != '' ? (
          <span>
            {beforeStr}
            <span style={{ color: '#f50' }}>{treeSearch}</span>
            {afterStr}
          </span>
        ) : (
          <span>{item?.name}</span>
        );

      if (item?.children && item?.children?.length > 0) {
        return (
          <TreeSelect.TreeNode
            title={
              <span>
                <MyIcon type={item?.icon} />
                &nbsp;
                {title}
              </span>
            }
            key={item?.id}
            value={item?.id}
            searchTitle={item?.name}
            companyID={item?.companyID}
            itemRef={{ ...item }}
            disabled={item?.id == detailInfoData?.id ? true : false}
          >
            {handleSelectTree(item.children)}
          </TreeSelect.TreeNode>
        );
      } else {
        return (
          <TreeSelect.TreeNode
            title={
              <span>
                <MyIcon type={item?.icon} />
                &nbsp;
                {title}
              </span>
            }
            key={item?.id}
            value={item?.id}
            searchTitle={item?.name}
            companyID={item?.companyID}
            itemRef={{ ...item }}
            disabled={item?.id == detailInfoData?.id ? true : false}
          />
        );
      }
    });
  };

  // 新增编辑保存
  const saveResoucerAddData = () => {
    resourForm?.validateFields()?.then((values: any) => {
      addResoucerData?.run({ ...values, isOpen: 1 });
    });
  };

  // 新增 或者编辑 方法
  const addResoucerData = useRequest(
    (payload: any) => {
      if (detailInfoData && detailInfoData?.id) {
        let params = {
          ...payload,
          id: detailInfoData?.id,
          versionNum: detailInfoData?.versionNum,
          modifyerID: getUserID(),
          modifyPositionID: getPosIDs(),
          modifyDepartmentID: getUserDepID(),
          modifyCompanyID: getCompanyID(),
        };
        return addEditResoucer(params, 'edit');
      } else {
        let params = {
          ...payload,
        };
        return addEditResoucer(params, 'add');
      }
    },
    {
      manual: true,
      onSuccess: (res: any) => {
        if (res && res?.msgFlag) {
          message?.success(res?.msg);
          tableReload();
          onCloseModal();
        } else {
          message?.error(res?.msg);
        }
      },
    },
  );

  return (
    <>
      <OneModal
        open={true}
        getContainer={false}
        ref={ResourModalRef}
        title={editAddRows && editAddRows?.id ? '编辑资源菜单' : '添加资源菜单'}
        width={'40%'}
        onCancel={onClose}
        // className={cls(prefixModal)}
        bodyStyle={{
          padding: '5px 0px',
          // height: window.screen.height * 0.5,
        }}
        centered
        footer={
          <>
            <div>
              <Button onClick={onCloseModal}>取消</Button>
              <Button
                type={'primary'}
                onClick={saveResoucerAddData}
                loading={addResoucerData?.loading}
                disabled={MapList?.data?.msgFlag ? false : true}
                onMouseOut={(event: any) => {
                  event?.target?.nodeName == 'BUTTON' ? event?.target?.blur() : event.target.parentNode.blur();
                }}
              >
                保存
              </Button>
            </div>
          </>
        }
      >
        <Spin spinning={editAddRows?.id ? infoLoading : false}>
          <div className={pageStyles['fromView-styles']}>
            <Form layout="inline" form={resourForm}>
              <Row>
                <Col span={24}>
                  <Form.Item
                    name={'name'}
                    label="资源名称"
                    rules={[
                      {
                        required: true,
                        message: '请输入资源名称',
                      },
                    ]}
                    initialValue={detailInfoData && detailInfoData?.id ? detailInfoData.name : undefined}
                  >
                    <Input placeholder={'请输入资源名称'} allowClear />
                  </Form.Item>
                </Col>

                <Col span={24}>
                  <Form.Item name={'url'} label="资源路径" initialValue={detailInfoData && detailInfoData?.id ? detailInfoData.url : undefined}>
                    <Input placeholder={'请输入资源路径'} allowClear />
                  </Form.Item>
                </Col>

                <Col span={24}>
                  <Form.Item
                    name={'matchRoute'}
                    label="服务路由"
                    rules={[
                      {
                        required: true,
                        message: '请输入服务路由',
                      },
                    ]}
                    initialValue={detailInfoData && detailInfoData?.id ? detailInfoData.matchRoute : undefined}
                  >
                    <Input placeholder={'请输入服务路由'} allowClear />
                  </Form.Item>
                </Col>
                <Col span={24}>
                  <Form.Item
                    name="systemType"
                    label="系统类别"
                    rules={[
                      {
                        required: true,
                        message: '请选择系统类别',
                      },
                    ]}
                    initialValue={detailInfoData && detailInfoData?.id ? detailInfoData.systemType : 0}
                  >
                    <Select placeholder="请选择系统类别">
                      <Select.Option key={0} value={0}>
                        公共资源
                      </Select.Option>
                      <Select.Option key={1} value={1}>
                        采购系统
                      </Select.Option>
                      <Select.Option key={2} value={2}>
                        合同系统
                      </Select.Option>
                      <Select.Option key={3} value={3}>
                        资产系统
                      </Select.Option>
                      <Select.Option key={4} value={4}>
                        专家库
                      </Select.Option>
                    </Select>
                  </Form.Item>
                </Col>

                <Col span={24}>
                  <Form.Item
                    label="资源类型"
                    name="resourceType"
                    rules={[{ required: true, message: '请选择资源类型' }]}
                    initialValue={detailInfoData && detailInfoData?.id ? detailInfoData.resourceType : undefined}
                  >
                    <Select placeholder="请选择资源类型">
                      <Select.Option key={0} value={0}>
                        系统目录
                      </Select.Option>
                      <Select.Option key={1} value={1}>
                        业务菜单
                      </Select.Option>
                      {/* <Select.Option key={2} value={2}>
                        数据范围
                      </Select.Option>
                      <Select.Option key={3} value={3}>
                        功能操作
                      </Select.Option> */}
                    </Select>
                  </Form.Item>
                </Col>

                <Col
                  span={24}
                  style={{
                    display: 'flex',
                    justifyContent: 'center',
                    alignItems: 'center',
                  }}
                >
                  <Form.Item
                    style={{
                      flex: 'auto',
                      overflow: 'hidden',
                    }}
                    label="资源类别"
                    name="resourceStyle"
                    rules={[{ required: true, message: '请选择资源类别' }]}
                    initialValue={detailInfoData && detailInfoData?.id ? detailInfoData.resourceStyle : 0}
                  >
                    <Select
                      placeholder="请选择资源类别"
                      onChange={(checkValue: any) => {
                        if (checkValue == 0) {
                          setIsResoucerStyleTip(true);
                        } else {
                          setIsResoucerStyleTip(false);
                        }
                      }}
                    >
                      <Select.Option key={0} value={0}>
                        全部
                      </Select.Option>
                      <Select.Option key={1} value={1}>
                        电脑端
                      </Select.Option>
                      <Select.Option key={2} value={2}>
                        手机端
                      </Select.Option>
                    </Select>
                  </Form.Item>

                  {isResoucerStyleTip ? (
                    <Tooltip placement={'top'} title="电脑端和手机端都可使用！">
                      <div style={{ marginBottom: '10px' }}>
                        <a>
                          &nbsp;&nbsp;
                          <QuestionCircleOutlined />
                        </a>
                      </div>
                    </Tooltip>
                  ) : (
                    <></>
                  )}
                </Col>

                <Col span={24}>
                  <Form.Item
                    name={'serviceType'}
                    label={'业务模块'}
                    initialValue={detailInfoData && detailInfoData?.id ? detailInfoData.serviceType : undefined}
                    rules={[
                      {
                        required: true,
                        message: '请选择业务模块',
                      },
                    ]}
                  >
                    <TreeSelect
                      showSearch
                      treeNodeFilterProp={'searchTitle'}
                      placeholder="请选择业务模块"
                      allowClear
                      // onSearch={treeSearchValue}
                      dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
                      treeData={treeSelectIconTransform(MapList?.data?.obj?.[`${getTenantID()}0000`], <MyIcon type="ic-normal-zidianguanli" />)}
                      loading={MapList?.data?.msgFlag ? false : true}
                    />
                  </Form.Item>
                </Col>

                <Col span={24}>
                  <Form.Item
                    label="方法类型"
                    name="method"
                    rules={[{ required: true, message: '请选择方法类型' }]}
                    initialValue={detailInfoData && detailInfoData?.id ? detailInfoData?.method : undefined}
                  >
                    <Select placeholder="请选择方法类型">
                      <Select.Option key="ALL" value="ALL">
                        ALL
                      </Select.Option>
                      <Select.Option key="GET" value="GET">
                        GET
                      </Select.Option>
                      <Select.Option key="POST" value="POST">
                        POST
                      </Select.Option>
                      <Select.Option key="PUT" value="PUT">
                        PUT
                      </Select.Option>
                      <Select.Option key="DELETE" value="DELETE">
                        DELETE
                      </Select.Option>
                    </Select>
                  </Form.Item>
                </Col>

                <Col span={24}>
                  <Form.Item name={'pID'} label={'上级资源'} initialValue={editAddRows ? editAddRows?.detaID : undefined}>
                    <TreeSelect
                      showSearch
                      treeNodeFilterProp={'searchTitle'}
                      placeholder="请选择上级资源"
                      allowClear
                      onSearch={treeSearchValue}
                      // onSelect={getCompanIDOfpid}
                    >
                      {handleSelectTree(rouTreeData)}
                    </TreeSelect>
                  </Form.Item>
                </Col>

                <Col span={24}>
                  <Form.Item
                    label="图标"
                    name="icon"
                    rules={[{ required: true, message: '请填写图标或选择图标' }]}
                    initialValue={selectedIcon ? selectedIcon : detailInfoData && detailInfoData?.id ? detailInfoData?.icon : undefined}
                  >
                    <Input
                      placeholder="请输入图标或选择图标"
                      addonAfter={
                        <div>
                          <MyIcon type={selectedIcon ? selectedIcon : detailInfoData && detailInfoData?.id ? detailInfoData?.icon : ''} />
                        </div>
                      }
                      onChange={(e) => {
                        changeIcon(e?.target?.value);
                      }}
                    />
                  </Form.Item>
                </Col>

                <Col span={24}>
                  <Form.Item name={'i18nRoute'} label="国际化" initialValue={detailInfoData && detailInfoData?.id ? detailInfoData.i18nRoute : undefined}>
                    <Input placeholder={'请输入国际化'} allowClear />
                  </Form.Item>
                </Col>

                <Col span={24}>
                  <Form.Item
                    label="排序"
                    name="seq"
                    initialValue={detailInfoData && detailInfoData?.id ? detailInfoData?.seq : 0}
                    rules={[{ required: true, message: '请输入排序' }]}
                  >
                    <InputNumber placeholder="请输入排序" min={0} />
                  </Form.Item>
                </Col>

                <Col span={24}>
                  <Form.Item label="备注" name="remark" initialValue={detailInfoData && detailInfoData?.id ? detailInfoData?.remark : undefined}>
                    <Input placeholder="请输入备注" allowClear />
                  </Form.Item>
                </Col>
              </Row>
            </Form>
          </div>
        </Spin>
      </OneModal>
    </>
  );
};
